package com.boot.tinyproxy.client.utils;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;

/**
 * 网络代理工具
 */
public abstract class InternetProxyUtils {


    /**
     * 设置代理
     *
     * @param proxyAddr
     * @param proxyPort
     */
    public static Proxy createProxy(String proxyAddr, int proxyPort) {
        // 设置认证
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(null, "Abc@1234"
                        .toCharArray());
            }
        });
        // 设置HTTP代理
        Proxy proxy = new Proxy(Proxy.Type.SOCKS,
                new InetSocketAddress(proxyAddr, proxyPort));
        return proxy;
    }


    /**代理工厂
     * @param host
     * @param port
     * @param username
     * @param pwd
     * @return
     */
    public static HttpComponentsClientHttpRequestFactory getFactory(String host, int port,String username,String pwd) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(host, port),
                new UsernamePasswordCredentials(username, pwd)
        );

        HttpHost myProxy = new HttpHost(host, port);
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.setProxy(myProxy).setDefaultCredentialsProvider(credsProvider).disableCookieManagement();

        CloseableHttpClient httpClient = clientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }
}
